package com.example.helloworld;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class DisplayBetActivity extends Activity {
    private ArrayList<HashMap<String, String>> allBets;
    private ArrayList<String> allBetsList;
    private ArrayAdapter<String> myAdapter;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_bet);
        placeAdapter();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.display_bet, menu);
        return true;
    }
    
    private void placeAdapter(){
    	// TODO Get 10 bets in the max range
        allBets = com.Connections.DownloadBets.getBets();
        
        final ListView listView = (ListView) findViewById(R.id.betsList);
        
        //Add an item click event to accept bets from the ListView
        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // This should display a dialog confirming the bet
                // Not sure how to do that yet and not make it crash
                final ListView tempList = (ListView) findViewById(R.id.betsList);
                Toast.makeText(getApplicationContext(),  "Bet Amount: " + tempList.getAdapter().getItem(position), Toast.LENGTH_LONG).show();
            }
          }); 
        allBetsList = new ArrayList<String>();
        // Add data from the bets list to this array list
        if(allBets != null){
        	for(HashMap<String, String> item: allBets){
        		String betString = "";
        		betString += "Amount: " + item.get("value") + ", ";
        		betString += "Bettor: " + item.get("bettorID") + ", ";
        		betString += "Bet ID: " + item.get("betID"); 
        		allBetsList.add(betString);
        	}
        }
        myAdapter = new ArrayAdapter<String>(this, R.layout.adapter_layout, allBetsList);
        // Create an adapter that contains the range array in order to populate the list
        listView.setAdapter(myAdapter);
    }
    
    public void filterBets(View view){
    	allBetsList.clear();
        // Get the lower end of the range
        final EditText minBet = (EditText) findViewById(R.id.minText);
        minBet.getText().toString();
        if(minBet.getText().toString().length() == 0){
        	Toast.makeText(getApplicationContext(),  "Invalid minimum.", Toast.LENGTH_LONG).show();
        	return;
        }
        final int min = Integer.parseInt(minBet.getText().toString());
        
        //Get the higher end of the range
        final EditText maxBet = (EditText) findViewById(R.id.maxText);
        if(maxBet.getText().toString().length() == 0){
        	Toast.makeText(getApplicationContext(),  "Invalid maximum.", Toast.LENGTH_LONG).show();
        	return;
        }
        final int max = Integer.parseInt(maxBet.getText().toString());
        
        // Start the DB connection on a separate, asynchronous thread
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        DownloadBets comObject = null;
        // Test to see if the network is actually connected
        if (networkInfo != null && networkInfo.isConnected()) {
        	comObject = new DownloadBets();
        	comObject.execute(min, max);
        } else {
            Toast.makeText(getApplicationContext(), "No network connection available.", Toast.LENGTH_LONG).show();
        }
        
        // There was some problem downloading bets, so notify the user and exit the method
    	if(comObject == null){
    		Toast.makeText(getApplicationContext(), "There was an error downloading bets.", Toast.LENGTH_LONG).show();
    		return;
    	}
    }
    
    private class DownloadBets extends AsyncTask<Integer, Integer, ArrayList<HashMap<String, String>>>{

    	// URLs where the php code is located
    	// JSON arrays are passed to the PHP pages in order to get data
    	// Constants used to identify the proper URLs for grabbing data
    	private static final String url_root = "http://rsl.lib.fit.edu/android_connect/";
    	private static final String url_getBetRange = url_root + "bet_read_range.php";
    	private static final String url_getAllBets = url_root + "bet_read_all.php";
    	
    	// Limit the amount of bets that can be retrieved for UI purposes and 
    	private static final int MAX_BETS = 10;
    	
    	// Necessary variables.
    	private JSONArray bets = null;
    	private JSONParser jParser = new JSONParser();
    	private ArrayList<HashMap<String, String>> betsList;
    		
    	// JSON node names
    	// These nodes identify different fields and objects in the JSON data
    	private static final String TAG_SUCCESS = "success";
    	private static final String TAG_BETS = "bets";
    	private static final String TAG_BETID = "betID";
    	private static final String TAG_BETTORID = "bettorID";
    	private static final String TAG_ACCEPTORID = "acceptorID";
    	private static final String TAG_VALUE = "value";
    	
    	
    	/**
    	 * betsList accessor method
    	 *
    	 * @return a list of all bets.
    	 */
    	public ArrayList<HashMap<String, String>> getBets() {
    		return betsList;
    	}
    	
    	@Override
    	protected ArrayList<HashMap<String, String>> doInBackground(Integer... range) {
    		// Build parameters.
    		List<NameValuePair> params = new ArrayList<NameValuePair>();
    		params.add(new BasicNameValuePair("minBet", Integer.toString(range[0])));
    		params.add(new BasicNameValuePair("maxBet", Integer.toString(range[1])));
    		params.add(new BasicNameValuePair("MAX_BETS", Integer.toString(MAX_BETS)));
    		// getting JSON string from URL
    		JSONObject json = jParser.makeHttpRequest(url_getBetRange, "GET", params);
    		try {
    			// Check the SUCCESS TAG to see if the http request worked
    			int success = json.getInt(TAG_SUCCESS);
    			
    			if (success == 1) {
    				// bets found
    				// Get array of bets
    				bets = json.getJSONArray(TAG_BETS);
    				
    				// loop through all bets
    				for(int i = 0; i < bets.length(); i++) {
    					JSONObject c = bets.getJSONObject(i);
    					
    					// Store each JSON item into a variable
    					String betID = c.getString(TAG_BETID);
    					String bettorID = c.getString(TAG_BETTORID);
    					String acceptorID = c.getString(TAG_ACCEPTORID);
    					String value = c.getString(TAG_VALUE);
    					
    					// create a new HashMap to be used for storing a bet
    					HashMap<String, String> map = new HashMap<String, String>();
    					
    					// add each child to the hashmap
    					map.put(TAG_BETID, betID);
    					map.put(TAG_BETTORID, bettorID);
    					map.put(TAG_ACCEPTORID, acceptorID);
    					map.put(TAG_VALUE, value);
    					
    					// add HashList to ArrayList
    					if(betsList == null){
    						betsList = new ArrayList<HashMap<String, String>>();
    					}
    					betsList.add(map);
    				}
    			} else {
    				// no bets found
    				// bets will be null
    			}
    		} catch (JSONException e) {
    			e.printStackTrace();
    		}
    		// Return the ArrayList of hash maps to be used in the onPostExecute() methdo
    		return betsList;
    	}
    	
    	/*
    	 * This method only executes after the AsyncTask has finished the 
    	 * doInBackground() method. The result of that method is passed as the parameter
    	 * to the this onPostExecute() method.
    	 * This method is also when the AsyncTask synchronizes with the main UI thread
    	 */
    	@Override
    	protected void onPostExecute(ArrayList<HashMap<String, String>> result){
    		super.onPostExecute(result);
    		
    		// Use the post execute method to update the UI thread
            allBetsList = new ArrayList<String>();
            // Add data from the bets list to this array list
            if(result != null){
            	for(HashMap<String, String> item: result){
            		String betString = "";
            		betString += "Amount: " + item.get("value") + ", ";
            		betString += "Bettor: " + item.get("bettorID") + ", ";
            		betString += "Bet ID: " + item.get("betID"); 
            		allBetsList.add(betString);
            	}
            }
            // Try to update the adapater view
            final ListView listView = (ListView) findViewById(R.id.betsList);
            myAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.adapter_layout, allBetsList);
            listView.setAdapter(myAdapter);
            myAdapter.notifyDataSetChanged();
    		// Alter the main, UI thread when the database connection is finished.
    		Toast.makeText(getApplicationContext(), "Loading bets done!", Toast.LENGTH_LONG).show();
    		this.cancel(true);
    	}
    }
}
